<script setup lang="ts">
//跳转
import {ref} from "vue";

let show = defineModel('modelValue');

const props = defineProps({
  title: {
    default: "",
    type: String
  },
  description: {
    default: "",
    type: String
  },
  time: {
    default: 5,
    type: Number
  },
  url: {
    default: "",
    type: String
  },
})

const router = useRouter();
const timeThis = ref(props.time)
let intervalId = "";
let setTimeoutId = "";
watch(show, (newValue) => {
  if (newValue) {
    // 创建定时器，每秒执行一次
    timeThis.value = props.time;
    intervalId = setInterval(() => {
      if (timeThis.value <= 0) {
        timeThis.value = 0;
      } else {
        timeThis.value--;
      }
    }, 1000);

    // 使用 setTimeout 在 5 秒后关闭定时器
    setTimeoutId = setTimeout(() => {
      router.push(props.url); // 导航到特定的帖子
      closeInterval();
    }, timeThis.value * 1000);
  } else {
    closeInterval();
  }
}, {immediate: true});

function close() {
  show.value = false;
  closeInterval();
}

function closeInterval() {
  if (intervalId) {
    clearInterval(intervalId);
  }
  if (setTimeoutId) {
    clearInterval(setTimeoutId);
  }
}

function moveTo() {
  show.value = false;
  router.push(props.url); // 导航到特定的帖子
}
</script>

<template>
  <div class="move-to-box">
    <el-dialog
        v-model="show"
        :title="title+'提醒'"
        width="500"
        :before-close="close">
      <div class="tips">{{ description }}({{ timeThis }}秒后自动跳转)</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="close">关 闭</el-button>
          <el-button type="primary" @click="moveTo">
            立即跳转
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.move-to-box{


  .tips{
    font-weight: bolder;
    font-size: 1.1rem;
  }
}
</style>